/**
 * @param {number[]} nums
 * @return {number}
 */

var reversePairs = function (nums) {
  let ret = 0;
  function getResult(nums, l, r) {
    if (l >= r) return;
    let mid = (l + r) >> 1;
    getResult(nums, l, mid);
    getResult(nums, mid + 1, r);


    let x = l, y = mid + 1,
      // 临时数组
      k = 0,
      temp = [];
    while (x <= mid || y <= r) {
      if ((y > r) || (x <= mid && nums[x] <= nums[y])) { // 左侧小于右侧
        temp[k++] = nums[x++];
      } else { // 左侧值大于右侧值
        temp[k++] = nums[y++];
        ret += mid - x + 1; // 左侧后面剩余的个数
      };
    }
    for (let i = l; i <= r; i++) {
      nums[i] = temp[i - l];
    }
  };
  getResult(nums, 0, nums.length - 1);
  return ret;
};